{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Ow8CQmZIV8Yn"
      },
      "source": [
        "# Link Prediction\n",
        "\n",
        "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/dmlc/dgl/blob/master/notebooks/stochastic_training/link_prediction.ipynb) [![GitHub](https://img.shields.io/badge/-View%20on%20GitHub-181717?logo=github&logoColor=ffffff)](https://github.com/dmlc/dgl/blob/master/notebooks/stochastic_training/link_prediction.ipynb)\n",
        "\n",
        "This tutorial will show how to train a multi-layer GraphSAGE for link\n",
        "prediction on [CoraGraphDataset](https://data.dgl.ai/dataset/cora_v2.zip).\n",
        "The dataset contains 2708 nodes and 10556 edges.\n",
        "\n",
        "By the end of this tutorial, you will be able to\n",
        "\n",
        "-  Train a GNN model for link prediction on target device with DGL's\n",
        "   neighbor sampling components.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "onVijYWpWlMj"
      },
      "source": [
        "## Install DGL package"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QcpjTazg6hEo"
      },
      "outputs": [],
      "source": [
        "# Install required packages.\n",
        "import os\n",
        "import torch\n",
        "os.environ['TORCH'] = torch.__version__\n",
        "os.environ['DGLBACKEND'] = \"pytorch\"\n",
        "\n",
        "# Install the CPU version in default. If you want to install CUDA version,\n",
        "# please refer to https://www.dgl.ai/pages/start.html and change runtime type\n",
        "# accordingly.\n",
        "device = torch.device(\"cpu\")\n",
        "!pip install --pre dgl -f https://data.dgl.ai/wheels-test/repo.html\n",
        "\n",
        "try:\n",
        "    import dgl\n",
        "    import dgl.graphbolt as gb\n",
        "    installed = True\n",
        "except ImportError as error:\n",
        "    installed = False\n",
        "    print(error)\n",
        "print(\"DGL installed!\" if installed else \"DGL not found!\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OOKZxxT7W1Rz"
      },
      "source": [
        "## Loading Dataset\n",
        "`cora` is already prepared as `BuiltinDataset` in **GraphBolt**.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RnJkkSKhWiUG"
      },
      "outputs": [],
      "source": [
        "dataset = gb.BuiltinDataset(\"cora-seeds\").load()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WxnTMEQXXKsM"
      },
      "source": [
        "Dataset consists of graph, feature and tasks. You can get the training-validation-test set from the tasks. Seed nodes and corresponding labels are already stored in each training-validation-test set. This dataset contains 2 tasks, one for node classification and the other for link prediction. We will use the link prediction task."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YCm8CGkOX9lK"
      },
      "outputs": [],
      "source": [
        "graph = dataset.graph.to(device)\n",
        "feature = dataset.feature.to(device)\n",
        "train_set = dataset.tasks[1].train_set\n",
        "test_set = dataset.tasks[1].test_set\n",
        "task_name = dataset.tasks[1].metadata[\"name\"]\n",
        "print(f\"Task: {task_name}.\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2y-P5omQYP00"
      },
      "source": [
        "## Defining Neighbor Sampler and Data Loader in DGL\n",
        "Different from the link prediction tutorial for full graph, a common practice to train GNN on large graphs is to iterate over the edges in minibatches, since computing the probability of all edges is usually impossible. For each minibatch of edges, you compute the output representation of their incident nodes using neighbor sampling and GNN, in a similar fashion introduced in the node classification tutorial.\n",
        "\n",
        "To perform link prediction, you need to specify a negative sampler. DGL provides builtin negative samplers such as `dgl.graphbolt.UniformNegativeSampler`. Here this tutorial uniformly draws 5 negative examples per positive example.\n",
        "\n",
        "Except for the negative sampler, the rest of the code is identical to the node classification tutorial.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LZgXGfBvYijJ"
      },
      "outputs": [],
      "source": [
        "from functools import partial\n",
        "datapipe = gb.ItemSampler(train_set, batch_size=256, shuffle=True)\n",
        "datapipe = datapipe.copy_to(device)\n",
        "datapipe = datapipe.sample_uniform_negative(graph, 5)\n",
        "datapipe = datapipe.sample_neighbor(graph, [5, 5])\n",
        "datapipe = datapipe.transform(partial(gb.exclude_seed_edges, include_reverse_edges=True))\n",
        "datapipe = datapipe.fetch_feature(feature, node_feature_keys=[\"feat\"])\n",
        "train_dataloader = gb.DataLoader(datapipe)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5sU_aulqYkwK"
      },
      "source": [
        "You can peek one minibatch from train_dataloader and see what it will give you.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "euEdzmerYmZi"
      },
      "outputs": [],
      "source": [
        "data = next(iter(train_dataloader))\n",
        "print(f\"MiniBatch: {data}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WYQqfrDWYtU0"
      },
      "source": [
        "## Defining Model for Node Representation\n",
        "Let’s consider training a 2-layer GraphSAGE with neighbor sampling. The model can be written as follows:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0qQbBwO7Y3-Q"
      },
      "outputs": [],
      "source": [
        "import dgl.nn as dglnn\n",
        "import torch.nn as nn\n",
        "import torch.nn.functional as F\n",
        "\n",
        "\n",
        "class SAGE(nn.Module):\n",
        "    def __init__(self, in_size, hidden_size):\n",
        "        super().__init__()\n",
        "        self.layers = nn.ModuleList()\n",
        "        self.layers.append(dglnn.SAGEConv(in_size, hidden_size, \"mean\"))\n",
        "        self.layers.append(dglnn.SAGEConv(hidden_size, hidden_size, \"mean\"))\n",
        "        self.hidden_size = hidden_size\n",
        "        self.predictor = nn.Sequential(\n",
        "            nn.Linear(hidden_size, hidden_size),\n",
        "            nn.ReLU(),\n",
        "            nn.Linear(hidden_size, 1),\n",
        "        )\n",
        "\n",
        "    def forward(self, blocks, x):\n",
        "        hidden_x = x\n",
        "        for layer_idx, (layer, block) in enumerate(zip(self.layers, blocks)):\n",
        "            hidden_x = layer(block, hidden_x)\n",
        "            is_last_layer = layer_idx == len(self.layers) - 1\n",
        "            if not is_last_layer:\n",
        "                hidden_x = F.relu(hidden_x)\n",
        "        return hidden_x"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "y23JppwHY5MC"
      },
      "source": [
        "## Defining Traing Loop\n",
        "The following initializes the model and defines the optimizer.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "omSIB_ePZACg"
      },
      "outputs": [],
      "source": [
        "in_size = feature.size(\"node\", None, \"feat\")[0]\n",
        "model = SAGE(in_size, 128).to(device)\n",
        "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QyWtzNZcZRgp"
      },
      "source": [
        "The following is the training loop for link prediction and evaluation.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "SccLVrjSZSkd"
      },
      "outputs": [],
      "source": [
        "from tqdm.auto import tqdm\n",
        "for epoch in range(3):\n",
        "    model.train()\n",
        "    total_loss = 0\n",
        "    for step, data in tqdm(enumerate(train_dataloader)):\n",
        "        # Get node pairs with labels for loss calculation.\n",
        "        compacted_seeds = data.compacted_seeds.T\n",
        "        labels = data.labels\n",
        "        node_feature = data.node_features[\"feat\"]\n",
        "        # Convert sampled subgraphs to DGL blocks.\n",
        "        blocks = data.blocks\n",
        "\n",
        "        # Get the embeddings of the input nodes.\n",
        "        y = model(blocks, node_feature)\n",
        "        logits = model.predictor(\n",
        "            y[compacted_seeds[0]] * y[compacted_seeds[1]]\n",
        "        ).squeeze()\n",
        "\n",
        "        # Compute loss.\n",
        "        loss = F.binary_cross_entropy_with_logits(logits, labels)\n",
        "        optimizer.zero_grad()\n",
        "        loss.backward()\n",
        "        optimizer.step()\n",
        "\n",
        "        total_loss += loss.item()\n",
        "\n",
        "    print(f\"Epoch {epoch:03d} | Loss {total_loss / (step + 1):.3f}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pxow2XSkZXoO"
      },
      "source": [
        "## Evaluating Performance with Link Prediction\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IMulfsnIZZVh"
      },
      "outputs": [],
      "source": [
        "model.eval()\n",
        "\n",
        "datapipe = gb.ItemSampler(test_set, batch_size=256, shuffle=False)\n",
        "datapipe = datapipe.copy_to(device)\n",
        "# Since we need to use all neghborhoods for evaluation, we set the fanout\n",
        "# to -1.\n",
        "datapipe = datapipe.sample_neighbor(graph, [-1, -1])\n",
        "datapipe = datapipe.fetch_feature(feature, node_feature_keys=[\"feat\"])\n",
        "eval_dataloader = gb.DataLoader(datapipe, num_workers=0)\n",
        "\n",
        "logits = []\n",
        "labels = []\n",
        "for step, data in tqdm(enumerate(eval_dataloader)):\n",
        "    # Get node pairs with labels for loss calculation.\n",
        "    compacted_seeds = data.compacted_seeds.T\n",
        "    label = data.labels\n",
        "\n",
        "    # The features of sampled nodes.\n",
        "    x = data.node_features[\"feat\"]\n",
        "\n",
        "    # Forward.\n",
        "    y = model(data.blocks, x)\n",
        "    logit = (\n",
        "        model.predictor(y[compacted_seeds[0]] * y[compacted_seeds[1]])\n",
        "        .squeeze()\n",
        "        .detach()\n",
        "    )\n",
        "\n",
        "    logits.append(logit)\n",
        "    labels.append(label)\n",
        "\n",
        "logits = torch.cat(logits, dim=0)\n",
        "labels = torch.cat(labels, dim=0)\n",
        "\n",
        "\n",
        "# Compute the AUROC score.\n",
        "from sklearn.metrics import roc_auc_score\n",
        "\n",
        "auc = roc_auc_score(labels.cpu(), logits.cpu())\n",
        "print(\"Link Prediction AUC:\", auc)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KoCoIvqAZeCS"
      },
      "source": [
        "## Conclusion\n",
        "In this tutorial, you have learned how to train a multi-layer GraphSAGE for link prediction with neighbor sampling."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "private_outputs": true,
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
